package com.sinosoft.perfect.common.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.sinosoft.perfect.common.system.BaseAction;
import com.sinosoft.perfect.system._.util.DownloadFileUtil;
import com.sinosoft.perfect.system._.util.Producer;


@SuppressWarnings("serial")
public class OperateFileAction extends BaseAction {

	private String fileName;
	
	private String showFileName;
	
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getShowFileName() {
		return showFileName;
	}
	public void setShowFileName(String showFileName) {
		this.showFileName = showFileName;
	}
	
	public String downloadFile() throws IOException {
		
		String tempFolder = ""+session.get("tempFolder");
		String file = (tempFolder +File.separator +fileName);
		DownloadFileUtil.downloadFile(file,showFileName,response,request);
		
		return null;
	}
	
	
	
	
	
	
	private File document;
	
	private String documentFileName, fileext, folder;
	
	public String fileUpload() throws Exception {
		response.setCharacterEncoding("utf-8");
		String tempFolder = request.getSession().getServletContext().getRealPath(folder);
		String tempId = Producer.generateIdOfTen();
		String tempName = tempFolder+File.separator+tempId;
		generateFile(document,tempName);
		response.getWriter().print(tempId);
		return null;
	}
	
	private void generateFile(File file, String tempName) throws Exception {
		InputStream uploadFile = new FileInputStream(document);
		int available = uploadFile.available();  
		byte[] b = new byte[available];
		FileOutputStream foutput = new FileOutputStream(new File(tempName));  
		uploadFile.read(b);  
		foutput.write(b);  
		foutput.flush();  
		foutput.close();  
		uploadFile.close(); 
	}

	public File getDocument() {
		return document;
	}

	public void setDocument(File document) {
		this.document = document;
	}

	public String getDocumentFileName() {
		return documentFileName;
	}

	public void setDocumentFileName(String documentFileName) {
		this.documentFileName = documentFileName;
	}

	public String getFileext() {
		return fileext;
	}

	public void setFileext(String fileext) {
		this.fileext = fileext;
	}

	public String getFolder() {
		return folder;
	}

	public void setFolder(String folder) {
		this.folder = folder;
	}
}
